package org.arch_learn.spring_cloud.sca_homework.service_code_8081.service.impl;

import org.apache.dubbo.config.annotation.Reference;
import org.arch_learn.spring_cloud.sca_homework.service_code_8081.service.ICodeService;
import org.arch_learn.spring_cloud.sca_homework.service_common_dependency.dubbo_api.ICodeDubboService;
import org.arch_learn.spring_cloud.sca_homework.service_common_dependency.dubbo_api.IEmailDubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class CodeService implements ICodeService {
    @Reference(check = false)
    private IEmailDubboService emailDubboService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Boolean createAndSendCode(String email) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            stringBuffer.append(new Random(10).nextInt());
        }
        String code = stringBuffer.toString();
        Boolean result = emailDubboService.sendEmail(email, code);
        if (result) {
            stringRedisTemplate.opsForValue().set("verification:" + email, code, 10, TimeUnit.MINUTES);
        }
        return result;
    }

    @Override
    public Integer validateCode(String email, String code) {
        Integer result;
        try {
            String realCode = stringRedisTemplate.opsForValue().get("verification:" + email);
            result = code.equals(realCode) ? 0 : 1;
        } catch (Exception e) {
            result = 2;
        }
        return result;
    }
}
